'use strict';

const Service = require('egg').Service;
const { parseTime } = require('../utils/index');
const { v4: uuidv4 } = require('uuid');
const { createDirectory } = require('../common/file');
const path =require('path');
const fs = require('fs')

class AdminService extends Service {
  async getSchools(page,limit) {
    const { ctx, app } = this;
    page = parseInt(page) || 1;
    limit = parseInt(limit) || 10;
    let offset = (page - 1) * limit
    //执行SQL语句
    const total = await app.mysql.query('SELECT COUNT(*) AS total FROM school');
    const result = await app.mysql.query('SELECT school_id,school_name,school.create_time,address,area_id,area_name FROM `school`,area WHERE school.area_code =area.area_id ORDER BY school.create_time DESC LIMIT ?,?', [offset, limit]);
    return ctx.body = { code: 200, msg: '', status: 'success', data: result,total:total[0].total };
  }

  async getShops(page,limit) {
    const { ctx, app } = this;
    page = parseInt(page) || 1;
    limit = parseInt(limit) || 10;
    let offset = (page - 1) * limit
    //执行SQL语句
    const total = await app.mysql.query('SELECT COUNT(*) AS total FROM school');
    const result = await app.mysql.query('SELECT shop_name,shop.shop_id,shop.address,phone,shop.create_time,school_name,username,password FROM `shop`,shopkeeper,school WHERE shop.shopkeeper_id = shopkeeper.shopkeeper_id  AND shop.school_id = school.school_id ORDER BY shop.create_time DESC LIMIT ?,?', [offset, limit]);
    return ctx.body = { code: 200, msg: '', status: 'success', data: result,total:total[0].total};

  }

  async getAreas(page,limit) {
    const { ctx, app } = this;
    page = parseInt(page) || 1;
    limit = parseInt(limit) || 10;
    let offset = (page - 1) * limit
    //执行SQL语句
    const total = await app.mysql.query('SELECT COUNT(*) AS total FROM school');
    const result = await app.mysql.query('SELECT * FROM `area` ORDER BY create_time DESC  LIMIT ?,?', [offset, limit]);
    return ctx.body = { code: 200, msg: '', status: 'success', data: result,total:total[0].total };

  }

  async addSchool(data) {
    const { ctx, app } = this;
    const school_id = uuidv4();
    const create_time = parseTime(new Date());
    const {school_name,address,area_code} = data;
    const saveResult = await this.app.mysql.insert('school',{
      school_id,
      area_code,
      school_name,
      create_time,
      address
    });
    if(saveResult.affectedRows !== 1){
      return ctx.body = { code: 200, msg: '插入学校数据失败！', status: 'failure' };
    }
    const filePath = path.join(__dirname,'../','/public/uploads',school_id.substring(0,8))
    const fileResult = createDirectory(filePath);
    if(fileResult){
      return ctx.body = { code: 200, msg: '', status: 'success', data: {schoolId:school_id} };
    }else{
      return ctx.body = { code: 200, msg: '创建学校文件存储目录失败！', status: 'failure' };
    }
  }

  async addShop(data) {
    const { ctx, app } = this;
     const shop_id = uuidv4();
     const shopkeeper_id = uuidv4();
     const {school_id,username,password,shop_name,address,phone} = data;
     //插入店主表
     const shopkeeperInsert = await app.mysql.insert('shopkeeper',{
      shopkeeper_id,
      username,
      password,
      createTime:parseTime(new Date()),
      shop_id
    });
     //插入店铺表
     const shopInsert = await app.mysql.insert('shop',{
       shop_id,
       school_id,
       shop_name,
       address,
       phone,
       create_time:parseTime(new Date()),
       shopkeeper_id
     });
     
     if(shopInsert.affectedRows !== 1 && shopkeeperInsert.affectedRows !== 1){
      return ctx.body = { code: 200, msg: '插入店铺数据失败！', status: 'failure' };
     }
     const filePath = path.join(__dirname,'../','/public/uploads',`/${school_id.substring(0,8)}`,`/${shop_id.substring(0,8)}`);
     const fileResult = createDirectory(filePath);
     if(fileResult){
      return ctx.body = { code: 200, msg: '', status: 'success', data: {shopId:shop_id} };
    }else{
      return ctx.body = { code: 200, msg: '创建店铺存储目录失败！', status: 'failure' };
    }
  }

  async addArea(data) {
    const { ctx, app } = this;
    const {area_name} = data;
    const area_id = uuidv4();
    const areaInsert = await app.mysql.insert('area',{
      area_id,
      create_time:parseTime(new Date()),
      area_name
    });
    if(areaInsert.affectedRows == 1){
      return ctx.body = { code: 200, msg: '', status: 'success', data: {areaId:area_id} };
    }else{
      return ctx.body = { code: 200, msg: '插入区域数据失败！', status: 'failure' };
    }
  }

  async deleteSchool(school_id) {
    const { ctx, app } = this;
    if(!school_id || typeof school_id !='string'){
      return ctx.body = { code: 200, msg: '学校ID不能为空！', status: 'failure' };
    }
    const result =await app.mysql.delete('school',{school_id});
    if(result.affectedRows == 1){
      // //删除目录
      // const filePath = path.join(__dirname,'../','/public/uploads',school_id.substring(0,8));
      // fs.unlinkSync(filePath);
      return { code: 200, msg: '', status: 'success' }
    }else{
      return { code: 200, msg: '删除学校失败 请刷新页面重试!', status: 'failure' }
    }
  }

  async deleteShop(shop_id) {
    const { ctx, app } = this;
    if(!shop_id || typeof shop_id !='string'){
      return ctx.body = { code: 200, msg: '店铺ID不能为空！', status: 'failure' };
    }
    const result =await app.mysql.delete('shop',{shop_id});
    const shopkeeperDelete =await app.mysql.delete('shopkeeper',{shop_id});
    if(result.affectedRows === 1){
      return { code: 200, msg: '', status: 'success' }
    }else{
      return { code: 200, msg: '删除店铺失败 请刷新页面重试!', status: 'failure' }
    }
  }

  async deleteArea(area_id) {
    const { ctx, app } = this;
    if(!area_id || typeof area_id !='string'){
      return ctx.body = { code: 200, msg: '区域ID不能为空！', status: 'failure' };
    }
    const result =await app.mysql.delete('area',{area_id});
    if(result.affectedRows === 1){
      return { code: 200, msg: '', status: 'success' }
    }else{
      return { code: 200, msg: '删除区域失败 请刷新页面重试!', status: 'failure' }
    }
  }

  async getSimpleOrders(page,limit){
    const { ctx, app } = this;
    page = parseInt(page) || 1;
    limit = parseInt(limit) || 10;
    let offset = (page - 1) * limit;
    //执行SQL语句
    const total = await app.mysql.query('SELECT COUNT(*) AS total FROM orders');
    const result = await app.mysql.query('SELECT order_id AS orderId,shop_name AS shopName,address,program,`status`,complete_time AS completeTime,price,orders.create_time AS createTime FROM `orders`,shop WHERE orders.shop_id = shop.shop_id  ORDER BY orders.create_time DESC LIMIT ?,?', [offset, limit]);
    return ctx.body = { code: 200, msg: '', status: 'success', data: result,total:total[0].total };
  }

  async getOrder(){

  }

  async putSchool(school_id,data) {

  }

  async putShop(shop_id,data) {

  }

  async putArea(area_id,data) {

  }
}

module.exports = AdminService;
